package com.ton.utils;

import com.alibaba.fastjson.JSON;
import com.kypj.frame.common.log.Log;
import com.kypj.frame.db.MyExcepiton;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


public class ResponseUtil {
    public static final String SUCCESS = "0";
    public static final String FAIL = "-1";

    public static void writeJSON(Object obj, HttpServletResponse resp) {
        try {

            String json = JSON.toJSONString(obj);
            if (Log.debug) Log.debug(json);
            resp.setCharacterEncoding("UTF-8");

            resp.setHeader("Content-Type", "application/json");
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().print(json);
        } catch (Exception e) {
            throw new MyExcepiton();
        }
    }


    public static String getJSON(Object obj) {
        try {
            String json = JSON.toJSONString(obj);
            return json;
        } catch (Exception e) {
            throw new MyExcepiton(e);
        }
    }

    public static void writeJSON(String json, HttpServletResponse resp) {
        try {
            if (Log.debug) Log.debug(json);
            resp.setCharacterEncoding("UTF-8");
            resp.getWriter().print(json);
        } catch (Exception e) {
            throw new MyExcepiton(e);
        }
    }

    public static void writeStringJsonFlag(String val, HttpServletResponse resp) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("flag", val);
        writeJSON(map, resp);
    }

    public static void writeString(String val, HttpServletResponse resp) {
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        try {
            if (Log.debug) Log.debug(val);
            resp.getWriter().print(val);
        } catch (IOException e) {
            throw new MyExcepiton(e);
        }
    }

    public static void addWeixinCookie(HttpServletResponse response, String accessKey) {
        Cookie cookie = new Cookie("accessKey", accessKey);
        cookie.setPath("/");
        int expireSecond = 3600;
        if (expireSecond > 0) cookie.setMaxAge(expireSecond);
        response.addCookie(cookie);
    }

}
